import { createRouter, createWebHistory } from 'vue-router'
import MainPage from '@/page/MainPage.vue'
import MyPage1 from '@/page/index/MyPage1.vue'
import MyPage2 from '@/page/index/MyPage2.vue'
import MyPage3 from '@/page/index/MyPage3.vue'
import LoginPage from '@/page/LoginPage.vue'
import TestApp from '@/page/app/TestApp.vue'
import { isLogin } from '@/stores/loginStore'
import IndexPage from '@/page/index/IndexPage.vue'
import SettingPage from '@/page/setting/SettingPage.vue'
import PrivacyPage from '@/page/privacy/PrivacyPage.vue'
import AboutPage from '@/page/about/AboutPage.vue'

const myRouter = createRouter({
  //工作模式
  history: createWebHistory(import.meta.env.BASE_URL),
  //路由列表，路径+组件
  routes: [
    {
      //默认路由
      path: '/',
      //必须写这个才行，不然不会默认选中首页
      redirect: '/main/page1',
    },
    {
      //主页
      path: '/main',
      component: MainPage,
      children: [
        {
          // index作为容器，不显示在URL中;空路径表示默认子路由
          path: '',
          component: IndexPage,
          redirect: '/page1',
          children: [
            {
              // 默认子路由，访问/main时自动跳转
              path: '',
              component: MyPage1,
            },
            {
              path: 'page1',
              component: MyPage1,
            },
            {
              path: 'page2',
              component: MyPage2,
            },
            {
              path: 'page3',
              component: MyPage3,
            },
          ],
        },
        {
          path: '/setting',
          component: SettingPage,
        },
        {
          path: '/privacy',
          component: PrivacyPage,
        },
        {
          path: '/about',
          component: AboutPage,
        },
      ],
    },
    {
      //登录页
      name: 'Login',
      path: '/login',
      component: LoginPage,
      meta: { notNeedToken: true },
    },
    {
      //我专门弄了个模块，专门供给外部使用的，可以自己设定逻辑，哪怕401错误，也不会自动跳转到登录页
      path: '/app',
      meta: { notNeedToken: true },
      children: [
        {
          path: 'testApp',
          component: TestApp,
          props: true,
        },
      ],
    },
  ],
})
//暴露出去，外部才能引用
export default myRouter
// 全局前置守卫
myRouter.beforeEach((to, from, next) => {
  const path: string = to.path ? to.path.toString() : ''
  if (to.meta.notNeedToken || path.indexOf('/app/') > 0) {
    // 不需要的token的路由
    console.log('此页面，不需要路由认证', path)
    next()
  } else {
    const hasToken: boolean = isLogin()
    if (hasToken) {
      // 正常跳转
      console.log('需要token且有token！')
      next()
    } else {
      // 重定向到登录页
      console.log('需要token且没有token！')
      next('/login')
    }
  }
})
